package org.gensokyo.crawler.luoli

import com.gargoylesoftware.htmlunit._
import com.gargoylesoftware.htmlunit.html._
import com.typesafe.scalalogging.slf4j.StrictLogging


object PinpaiHandler extends StrictLogging {

  import scalaj.collection.Imports._

  implicit val formats = org.json4s.DefaultFormats


  def handle(proxyIp: String, proxyPort: Int) = {

    logger.debug(s"""proxyIp=${proxyIp},proxyPort=${proxyPort}""")
    val (username, password, email) = getUserInfo
    logger.debug(s"username:${username} password:${password} email:${email}")

    var page: HtmlPage = null
    var webClient: WebClient = null
    try {
      logger.debug("start")
      webClient = new WebClient(BrowserVersion.FIREFOX_45, "proxyIp", proxyPort)
      webClient.getOptions.setTimeout(30 * 1000)
      webClient.getOptions.setThrowExceptionOnScriptError(false)
      webClient.getOptions.setThrowExceptionOnFailingStatusCode(false)
      webClient.setConfirmHandler(new ConfirmHandler() {
        def handleConfirm(page: Page, message: String): Boolean = {
          logger.debug(s"----------------------------------------")
          logger.debug(s"confirm message:${message}")
          logger.debug(s"----------------------------------------")
          true
        }
      })
      webClient.setAlertHandler(new AlertHandler() {
        override def handleAlert(page: Page, message: String): Unit = {
          logger.debug(s"----------------------------------------")
          logger.debug(s"alert message:${message}")
          logger.debug(s"----------------------------------------")
        }
      })
      //      webClient.getOptions.setJavaScriptEnabled(false)
      //      webClient.setJavaScriptTimeout(10L)
      val url1 = "http://pinpai9.com/?x=717149"
      val page1: HtmlPage = webClient.getPage(url1)
      if (page1.querySelector("#ERR_ACCESS_DENIED") != null) {
        throw new Exception("Squid proxy error!")
      }
      val page2: HtmlPage = webClient.getPage("http://pinpai9.com/forum.php?mod=viewthread&tid=45261")
      if (!stripSpace(page2.asText()).contains("您需要先登录才能继续本操作")) {
        logger.debug(s"page2.asText()=${stripSpace(page2.asText())}")
        throw new Exception("Not contain 您需要先登录才能继续本操作")
      }
      Thread.sleep(1000L)
      val page3: HtmlPage = webClient.getPage("http://pinpai9.com/member.php?mod=register")
      if (!stripSpace(page3.asText()).contains("确认密码")) {
        logger.debug(s"page3.asText()=${stripSpace(page3.asText())}")
        throw new Exception("Not contain 确认密码")
      }
      page3.querySelector("""input#czG0Er""").asInstanceOf[HtmlTextInput].setValueAttribute(username)
      Thread.sleep(500L)
      page3.querySelector("""input#sva0ev""").asInstanceOf[HtmlPasswordInput].setValueAttribute(password)
      Thread.sleep(500L)
      page3.querySelector("""input#F8cG82""").asInstanceOf[HtmlPasswordInput].setValueAttribute(password)
      Thread.sleep(500L)
      page3.querySelector("""input#PrRWAP""").asInstanceOf[HtmlTextInput].setValueAttribute(email)
      Thread.sleep(3000L)
      logger.debug(s"page3.asText()=${stripSpace(page3.asText())}")
      val page4: HtmlPage = page2.querySelector("""#registerformsubmit""").asInstanceOf[HtmlButton].click()
      Thread.sleep(5000L)
      logger.debug(s"page4.asText()=${stripSpace(page4.asText())}")


      logger.debug("deal over")
    } catch {
      case e: Exception => logger.error(e.getMessage, e)
    } finally {
      webClient.close()
    }
  }

  def deal = {
    handle("218.18.16.44", 8998)
  }

  def main(args: Array[String]): Unit = {
    deal
  }

}
